package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import
        com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.pojo.ApUser;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author frr
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断如果传入的用户名和密码不为空
        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {

//            Wrapper<ApUser> queryWrapper = new QueryWrapper<>();
//            ((QueryWrapper<ApUser>)queryWrapper).eq("phone", dto.getPhone());

            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

            if (null == apUser) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            String salt = apUser.getSalt();
            String pwd = dto.getPassword() + salt;
            pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(Charset.forName("UTF-8")));

            if (pwd.equals(apUser.getPassword())) {
                String token = AppJwtUtil.getToken((long) apUser.getId());
                apUser.setPassword("");
                apUser.setPassword("");

                Map<String, Object> result = new HashMap<>();
                result.put("user", apUser);
                result.put("token", token);

                return ResponseResult.okResult(result);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> result = new HashMap<>();

            result.put("token", token);

            return ResponseResult.okResult(result);

        }


    }
}
